package org.jcnc;

import com.sun.net.httpserver.HttpServer;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpExchange;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.net.InetSocketAddress;

public class SimpleHttpServer {

    public  static int PORT = 10251;
    public static void main(String[] args) throws Exception {

        SystemMonitorService systemMonitorService = new SystemMonitorService();

        HttpServer server = HttpServer.create(new InetSocketAddress(PORT), 0);

        // API Endpoint for getting system stats
        server.createContext("/api/system-stats", new HttpHandler() {
            @Override
            public void handle(HttpExchange exchange) throws IOException {
                String response = String.format("{\"cpuLoad\": %.2f, \"freeMemory\": %.2f, \"totalMemory\": %.2f, \"swapUsed\": %.2f, \"swapTotal\": %.2f}",
                        systemMonitorService.getCpuLoad(),
                        systemMonitorService.getFreeMemory(),
                        systemMonitorService.getTotalMemory(),
                        systemMonitorService.getSwapUsed(),
                        systemMonitorService.getSwapTotal());

                exchange.getResponseHeaders().set("Content-Type", "application/json");
                exchange.sendResponseHeaders(200, response.getBytes().length);
                try (OutputStream os = exchange.getResponseBody()) {
                    os.write(response.getBytes());
                }
            }
        });

        // Serving the HTML page from a static directory
        server.createContext("/", new HttpHandler() {
            @Override
            public void handle(HttpExchange exchange) throws IOException {
                // 从 classpath 根目录加载 index.html 资源（请确保 index.html 已放在 src/main/resources 下）
                InputStream is = SimpleHttpServer.class.getResourceAsStream("/index.html");
                if (is == null) {
                    // 未找到资源，返回 404 状态码
                    exchange.sendResponseHeaders(404, -1);
                    return;
                }
                // 将 InputStream 转为 String (Java 9+ 可直接使用 readAllBytes())
                String htmlContent = new String(is.readAllBytes(), StandardCharsets.UTF_8);

                // 设置响应头，指定内容类型和字符编码
                exchange.getResponseHeaders().set("Content-Type", "text/html; charset=UTF-8");
                exchange.sendResponseHeaders(200, htmlContent.getBytes(StandardCharsets.UTF_8).length);
                try (OutputStream os = exchange.getResponseBody()) {
                    os.write(htmlContent.getBytes(StandardCharsets.UTF_8));
                }
            }
        });

        server.start();
        System.out.println("Server started on http://localhost:"+PORT);
    }
}
